package com.tiny.string;

import java.util.Stack;

/**
 * 躲了一辈子雨，雨会不会很难过。
 * </p>
 * Created by zhumenglong on 2018/1/5.
 */
public class ReversString {

    public static String s = "ABCDEFGHIJKLMN";

    public static void main(String[] args) {
        System.out.println(reverse1(s));
        System.out.println(revers2(s));
        System.out.println(reverse3(s));
        System.out.println(reverse4(s));
        System.out.println(reverse5(s));
    }

    /**
     * 使用递归实现
     */
    public static String reverse1(String s){
        int length = s.length();
        if(length<=1)
            return s;
        String left = s.substring(0,length/2);
        String right = s.substring(length/2,length);
        return reverse1(right)+reverse1(left);
    }

    /**
     * 拼接字符串
     */
    public static String revers2(String s){
        int length = s.length();
        String reverse = "";
        for (int i = 0; i < length; i++)
            reverse = s.charAt(i) + reverse;
        return reverse;
    }

    /**
     * 利用数组倒叙输出
     */
    public static String reverse3(String s){
        char[] array = s.toCharArray();
        String reverse = "";
        for (int i = array.length-1;i>=0;i--)
            reverse += array[i];
        return reverse;
    }

    /**
     * 利用位异或操作，交换两头数据
     */
    public static String reverse4(String s){
        char[] str = s.toCharArray();

        int begin = 0;
        int end = s.length() - 1;
        while (begin < end){
            str[begin] = (char) (str[begin] ^ str[end]);
            str[end] = (char) (str[begin] ^ str[end]);
            str[begin] = (char) (str[end] ^ str[begin]);
            begin++;
            end--;
        }
        return new String(str);
    }

    /**
     * 利用栈结构
     */
    public static String reverse5(String s){
        char[] str = s.toCharArray();
        Stack<Character> stack = new Stack<Character>();
        for (int i = 0; i < str.length; i++)
            stack.push(str[i]);

        String reversed = "";
        for (int i = 0; i < str.length; i++)
            reversed += stack.pop();

        return reversed;
    }


}
